package model;

import Bean.Account;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class AdminModel extends RootModel
{

    public ResultSetTableModel getAllAccount()
    {
        try
        {
            ConnectDB.connect();
            state = ConnectDB.getState();
            res = state.executeQuery("SELECT user, priority FROM account;");
            rstm = new ResultSetTableModel(res, 7);
            res.close();
            ConnectDB.close();
        }
        catch (SQLException ex)
        {
            Logger.getLogger(CustomerManagerModel.class.getName()).log(Level.SEVERE, null, ex);
        }
        finally
        {
            return rstm;
        }
    }

    public void addAccount(Account acc)
    {
        try
        {
            ConnectDB.connect();
            prst = ConnectDB.getConnect().prepareStatement("INSERT INTO `account` (`user`, `pass`, `priority`) VALUES (?, ?, ?);");
            prst.setString(1, acc.getUser());
            prst.setString(2, acc.getPass());
            prst.setString(3, acc.getType());
            prst.executeUpdate();
        }
        catch (SQLException ex)
        {
            Logger.getLogger(CustomerManagerModel.class.getName()).log(Level.SEVERE, null, ex);
        }
        finally
        {
            ConnectDB.close();
        }
    }

    public void delAccount(String user)
    {
        try
        {
            ConnectDB.connect();
            prst = ConnectDB.getConnect().prepareStatement("DELETE FROM `account` WHERE `user`=?;");
            prst.setString(1, user);
            prst.executeUpdate();
        }
        catch (SQLException ex)
        {
            Logger.getLogger(CustomerManagerModel.class.getName()).log(Level.SEVERE, null, ex);
        }
        finally
        {
            ConnectDB.close();
        }
    }

    public Boolean existUser(String user)
    {
        try
        {
            ConnectDB.connect();
            state = ConnectDB.getState();
            res = state.executeQuery("SELECT user FROM account;");
            while (res.next())
            {
                String userDb = res.getString("User");
                if (user.equals(userDb))
                {
                    res.close();
                    ConnectDB.close();
                    return true;
                }
            }
            res.close();
            ConnectDB.close();
        }
        catch (SQLException ex)
        {
            Logger.getLogger(CustomerManagerModel.class.getName()).log(Level.SEVERE, null, ex);
        }
        return false;

    }
}
